package com.wxmit.module.system.api;

import cn.hutool.core.collection.CollUtil;
import com.wxmit.framework.satoken.core.util.StpUserUtil;
import com.wxmit.module.system.service.ISysRoleService;
import com.wxmit.system.api.PermissionApi;
import com.wxmit.system.domain.DeptDataPermissionRespDTO;
import com.wxmit.system.domain.SysRoleDTO;
import com.wxmit.system.enums.DataPermissionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description PermissionApiImpl
 * @Author huangxiong
 * @Date 2022/7/15 10:25
 * @Version V1.0
 */
@Service
public class PermissionApiImpl implements PermissionApi {

    @Autowired
    private ISysRoleService sysRoleService;


    @Override
    public DeptDataPermissionRespDTO getDeptDataPermissionByRoleKeys(List<String> roleKeys) {
        DeptDataPermissionRespDTO permissionResp = new DeptDataPermissionRespDTO();
        if(StpUserUtil.isAdmin()){
            permissionResp.setAll(true);
            return permissionResp;
        }
        List<SysRoleDTO> roleCacheValue = sysRoleService.getRoleCacheValue(roleKeys);
        if(CollUtil.isEmpty(roleCacheValue)){
            permissionResp.setSelf(true);
        }else{
            roleCacheValue.forEach(it -> {
                switch (DataPermissionEnum.getByCode(it.getDataScope())) {
                    case ALL:
                        permissionResp.setAll(true);
                        break;
                    case CUSTOM:
                        permissionResp.setDeptIds(new HashSet<>(it.getDeptIds()));
                        break;
                    case DEPT_AND_CHILD:
                        permissionResp.setSelfDeptTree(true);
                        break;
                    case DEPT:
                        permissionResp.setSelfDept(true);
                        break;
                    case SELF:
                        permissionResp.setSelf(true);
                        break;
                }
            });
        }
        return permissionResp;
    }
}
